package top.infopub.mgr.ic.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.ic.dao.ProgramPlanAttDao;
import top.infopub.mgr.ic.dao.ProgramPlanDao;
import top.infopub.mgr.ic.dao.ProgramPlanMileDao;
import top.infopub.mgr.ic.dao.ProgramPlanSubDao;
import top.infopub.mgr.ic.domain.ProgramPlanDomain;
import top.infopub.model.ic.ProgramPlan;
import top.infopub.mgr.ic.service.ProgramPlanService;
import top.infopub.mgr.ic.vo.ProgramPlanVo;
import top.infopub.model.ic.ProgramPlanAtt;
import top.infopub.model.ic.ProgramPlanMile;
import top.infopub.model.ic.ProgramPlanSub;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ProgramPlanServiceImpl extends GenericServiceImpl<ProgramPlan, String> implements
        ProgramPlanService {

    @Autowired
    private ProgramPlanDao programPlanDao;

    @Autowired
    private ProgramPlanSubDao programPlanSubDao;

    @Autowired
    private ProgramPlanMileDao programPlanMileDao;

    @Autowired
    private ProgramPlanAttDao programPlanAttDao;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Override
    public GenericDao<ProgramPlan, String> getDao() {
        return programPlanDao;
    }

    @Override
    public Page<ProgramPlanDomain> selectByDomainWhere(Page<ProgramPlanDomain> page, ProgramPlanVo programPlanVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProgramPlanDomain>) programPlanDao.selectByDomainWhere(programPlanVo);
    }

    @Override
    public Page<ProgramPlanDomain> selectMyCheckByDomainWhere(Page<ProgramPlanDomain> page, ProgramPlanVo programPlanVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ProgramPlanDomain>) programPlanDao.selectMyCheckByDomainWhere(programPlanVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProgramPlan(ProgramPlan programPlan, List<ProgramPlanMile> planMileList, List<ProgramPlanSub> programPlanSubList, String[] fileAtt) {
        //执行新增
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String programPlanId = IdFactory.getUUIDUpper();
        //添加programPlan表的信息
        if (StringUtils.isEmpty(programPlan.getId())) {
            programPlan.setId(programPlanId);
            String codes = "ic_program_plan";
            String generatorCode = codeGeneratorConfigService.generatorCode(codes);
            programPlan.setCodes(generatorCode);
            String processId = IdFactory.getUUIDUpper();
            programPlan.setProcessId(processId);
            programPlan.setAddBy(vo.getId());
            programPlan.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            programPlan.setUptBy(vo.getId());
            programPlan.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            //设置审批状态为1=审批中
            programPlan.setTypes("1");
            programPlan.setProcessStatus("1");
            programPlanDao.insert(programPlan);

            // TODO 注意 这里根据不同的业务分支判断条件 获得不同enum
            FlowTemplateEnum templateEnum = FlowTemplateEnum.IC_PROGRAM_PLAN;
            // 处理工作流数据
            wsFlowProcess.launch(templateEnum, programPlanId, processId, null);

        }
        //添加ProgramPlanSub表的信息
        if (programPlanSubList != null && programPlanSubList.size() > 0) {
            for (int i = 0; i < programPlanSubList.size(); i++) {
                ProgramPlanSub programPlanSub = programPlanSubList.get(i);
                programPlanSub.setProgramPlanId(programPlanId);
                programPlanSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                String programPlanSubId = IdFactory.getUUIDUpper();
                programPlanSub.setId(programPlanSubId);
                programPlanSubDao.insert(programPlanSub);
                //添加每个子项下的节点信息
                Iterator<ProgramPlanMile> mileIterator = planMileList.iterator();
                while (mileIterator.hasNext()) {
                    ProgramPlanMile programPlanMile = mileIterator.next();
                    //buildSubId比对，相同时添加
                    if (programPlanMile.getPlanSubId().equals(programPlanSub.getAddBy())) {
                        String programPlanMileId = IdFactory.getUUIDUpper();
                        programPlanMile.setId(programPlanMileId);
                        programPlanMile.setProgramPlanId(programPlanId);
                        programPlanMile.setPlanSubId(programPlanSubId);
                        programPlanMile.setAddBy(vo.getId());
                        programPlanMile.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
                        programPlanMileDao.insert(programPlanMile);
                        mileIterator.remove();
                    }
                }
                //insert到sub表的的数据中，AddBy存放buildSubId,此时需要更新AddBy的字段信息
                programPlanSub.setAddBy(vo.getId());
                programPlanSubDao.updateByIdSelective(programPlanSub);
            }
        }
        //添加附件表的信息
        List<ProgramPlanAtt> fileAtts = new ArrayList<>();
        if (fileAtt != null) {
            for (String file : fileAtt) {
                ProgramPlanAtt programPlanAtt = createFileAtt(vo, programPlanId, file);
                fileAtts.add(programPlanAtt);
            }
        }
        if (CollectionUtils.isNotEmpty(fileAtts)) {
            programPlanAttDao.batchInsert(fileAtts);
        }
    }

    private ProgramPlanAtt createFileAtt(AuthorizationVO vo, String programPlanId, String file) {
        // 资料信息数组
        String[] fileAttStr = file.split("\\|");
        ProgramPlanAtt fileAtt = new ProgramPlanAtt();
        if(StringUtils.isNotEmpty(fileAttStr[2])){
            fileAtt.setId(fileAttStr[2]);
        }else{
            fileAtt.setId(IdFactory.getUUIDUpper());
        }
        //项目id
        fileAtt.setProgramPlanId(programPlanId);
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        //后缀转小写
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."), fileAttStr[1].length()).toLowerCase();
        //文件名
        fileAtt.setFileName(fileName);
        //文件后缀
        fileAtt.setFileSuffix(suffix);
        //文件保存路径
        fileAtt.setFilePath(fileAttStr[3]);
        //添加人
        fileAtt.setAddBy(vo.getId());
        //添加时间
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        return fileAtt;
    }
    
    @Override
    public ProgramPlanDomain selectById(String id){
        return programPlanDao.selectById(id);
    }
}